package com.wxl.common.wiget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;


public class NestScrollColorChangeView extends NestedScrollView {

    private View colorChangeView;
    private int criticalValue;
    private int targetColor, color;
    private int mScrollY = 0;
    private int lastScrollY = 0;

    public NestScrollColorChangeView(@NonNull Context context) {
        super(context);
    }

    public NestScrollColorChangeView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public NestScrollColorChangeView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    public void setColorChangeView(View colorChangeView) {
        this.colorChangeView = colorChangeView;
    }

    public void setCriticalValue(int criticalValue) {
        this.criticalValue = criticalValue;
    }

    public void setTargetColor(int targetColor) {
        color = ContextCompat.getColor(getContext(), targetColor) & 0x00ffffff;
        this.targetColor = targetColor;
    }

    @Override
    protected void onScrollChanged(int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
        super.onScrollChanged(scrollX, scrollY, oldScrollX, oldScrollY);
        if (criticalValue <= lastScrollY) {
            colorChangeView.setBackgroundColor(ContextCompat.getColor(getContext(), targetColor));
            if(onScrollStateChanged != null){
                onScrollStateChanged.onStateChanged(State.CLOSE);
            }
        } else {
            colorChangeView.setBackgroundColor(ContextCompat.getColor(getContext(), android.R.color.transparent));
            if(onScrollStateChanged != null){
                onScrollStateChanged.onStateChanged(State.OPEN);
            }
        }

        if (lastScrollY < criticalValue) {
            scrollY = Math.min(criticalValue, scrollY);
            mScrollY = scrollY > criticalValue ? criticalValue : scrollY;
            colorChangeView.setBackgroundColor(((255 * mScrollY / criticalValue) << 24) | color);
            if(onScrollStateChanged != null){
                onScrollStateChanged.onStateChanged(State.MUDDLE);
            }
        }
        lastScrollY = scrollY;
    }


   public interface OnScrollStateChanged {
        void onStateChanged(State state);
    }

   public  enum State{
        CLOSE,
        OPEN,
        MUDDLE
    }


    private OnScrollStateChanged onScrollStateChanged;

    public void setOnScrollStateChanged(OnScrollStateChanged onScrollStateChanged) {
        this.onScrollStateChanged = onScrollStateChanged;
    }
}
